package com.moss.cloud.common.core.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.nio.charset.Charset;
import java.util.function.Consumer;

public class HttpUtil {
    /**
     * 构建GET请求
     * @param url
     * @param headersConsumer
     * 请求头参数示例：
     *          Consumer<HttpHeaders> consumer = httpHeaders -> {
     *                  httpHeaders.add("1","2");
     *                  httpHeaders.add("3","4");
     *          };
     * @return
     */
    public static String doGet(String url,Consumer<HttpHeaders> headersConsumer) {
        Mono<String> data = WebClient.builder()
                .build()
                .get()
                .uri(url).headers(headersConsumer)
                .acceptCharset(Charset.defaultCharset())
                .retrieve()
                .bodyToMono(String.class);
        return data.block();
    }

    /**
     * 构建POST请求
     * @param url 请求路径
     * @param map 参数
     * @param headersConsumer HTTP请求头设置
     * 请求头参数示例：
     *     Consumer<HttpHeaders> consumer = httpHeaders -> {
     *             httpHeaders.add("1","2");
     *             httpHeaders.add("3","4");
     *     };
     * @return String.class
     */
    public static String doPost(String url, MultiValueMap map, Consumer<HttpHeaders> headersConsumer) {
        Mono<String> data = WebClient.builder().baseUrl(url)
                .build()
                .post()
                .headers(headersConsumer)
                .body(BodyInserters.fromFormData(map))
                .acceptCharset(Charset.defaultCharset())
                .retrieve()
                .bodyToMono(String.class);
        return data.block();
    }
}
